package wang.xinqiu.mysqlcontrol.data

data class ErrorHandlingResult(
    val suggestion: String,
    val fixedQuery: String? = null,
    val severity: String = "error",
    val errorType: String = "unknown",
    val userAction: String = "请检查并重试",
    val autoRetry: Boolean = false,
    val retryDelay: Long = 1000L
)

class SmartErrorHandler {
    fun handleError(error: Throwable, context: String): ErrorHandlingResult {
        val errorMessage = error.message ?: "未知错误"
        
        return when {
            errorMessage.contains("syntax error", ignoreCase = true) -> {
                ErrorHandlingResult(
                    suggestion = "SQL语法错误，请检查语法",
                    errorType = "语法错误",
                    userAction = "检查SQL语句语法",
                    severity = "error"
                )
            }
            errorMessage.contains("table", ignoreCase = true) && errorMessage.contains("doesn't exist", ignoreCase = true) -> {
                ErrorHandlingResult(
                    suggestion = "表不存在，请检查表名",
                    errorType = "表不存在",
                    userAction = "确认表名是否正确",
                    severity = "error"
                )
            }
            errorMessage.contains("connection", ignoreCase = true) -> {
                ErrorHandlingResult(
                    suggestion = "连接错误，尝试重新连接",
                    errorType = "连接错误",
                    userAction = "检查网络连接",
                    autoRetry = true,
                    severity = "warning"
                )
            }
            else -> {
                ErrorHandlingResult(
                    suggestion = "执行出错：$errorMessage",
                    errorType = "执行错误",
                    userAction = "请检查并重试",
                    severity = "error"
                )
            }
        }
    }
    
    fun getSQLOptimizationSuggestions(query: String, error: String): List<String> {
        val suggestions = mutableListOf<String>()
        
        if (query.uppercase().contains("SELECT *")) {
            suggestions.add("避免使用 SELECT *，明确指定需要的列")
        }
        
        if (!query.uppercase().contains("LIMIT")) {
            suggestions.add("考虑添加 LIMIT 限制返回行数")
        }
        
        if (!query.uppercase().contains("WHERE") && query.uppercase().contains("SELECT")) {
            suggestions.add("添加 WHERE 条件以提高查询效率")
        }
        
        return suggestions
    }
}
